using System;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Collections.Generic;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

using RealDolmen.Helpers;
using RealDolmen.SharePoint.Helpers;
using RealDolmen.SharePoint.ListFeatures.Elements;
using RealDolmen.Controls;

[assembly: WebResource("RealDolmen.SharePoint.ListFeatures.Resources.ECB.ScriptLib.js", "application/x-javascript")]
[assembly: WebResource("RealDolmen.SharePoint.ListFeatures.Resources.ECB.ScriptOverride.js", "application/x-javascript")]
namespace RealDolmen.SharePoint.ListFeatures.Controls
{
    public class ListFeatureEcbMenuItem : ListFeatureMenuItem
    {
        public override string Location
        {
            get { return "EditControlBlock"; }
        }

        #region AddControl
        private StringBuilder stringBuilder;
        private string currentToolBarId = string.Empty;

        protected override void BeforeAddControls()
        {
            Control p = ControlHelper.GetClosestParent<ToolBar>(this);
            currentToolBarId = p.ClientID;
            stringBuilder = new StringBuilder();

            ClientScriptManager cs = Page.ClientScript;

            // Add the library if necessary
            if (!cs.IsClientScriptBlockRegistered(GetType(), "LF.ECB.ScriptLib"))
            {
                string script = cs.GetWebResourceUrl(GetType(), "RealDolmen.SharePoint.ListFeatures.Resources.ECB.ScriptLib.js");
                script = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>\n", script);
                cs.RegisterStartupScript(
                   GetType(), "LF.ECB.ScriptLib",
                   script, false);
            }

            // Add the override fix if necessary
            if (!cs.IsClientScriptBlockRegistered(GetType(), "LF.ECB.ScriptOverride"))
            {
                string script = cs.GetWebResourceUrl(GetType(), "RealDolmen.SharePoint.ListFeatures.Resources.ECB.ScriptOverride.js");
                script = string.Format("<script type=\"text/javascript\" src=\"{0}\" defer></script>\n", script);
                cs.RegisterStartupScript(
                   GetType(), "LF.ECB.ScriptOverride",
                   script, false);
            }
        }

        protected override void AddControl(Control control, int index, ListFeatureCustomActionElement customAction)
        {
            CreateJsButton(control);
        }

        #region Core Javascript
        private void CreateJsButton(Control control)
        {
            StringBuilder sbControl = new StringBuilder();
            HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sbControl));
            control.RenderControl(writer);

            stringBuilder.AppendLine("addEcbItem(");
            stringBuilder.AppendFormat("       [{0}],\n", sbControl);
            stringBuilder.AppendFormat("       '{0}');\n", currentToolBarId);
        }
        #endregion // Core Javascript

        protected override void AfterAddControls()
        {
            string output = stringBuilder.ToString();

            if (output.Length > 8)
            {
                Page.ClientScript.RegisterStartupScript(
                   GetType(),
                   Guid.NewGuid().ToString(),
                   output, true);
            }
        }

        #endregion // AddControl

        #region BuildControl
        protected override Control BuildControl(ListFeatureCustomActionElement customAction)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;

            string str2, str3;

            List<string> strings = new List<string>();
            strings.Add(SPHttpUtility.HtmlEncode(customAction.ParsedTitle));
            strings.Add(SPParser.ParseUrlPrefixInUrl(customAction.ImageUrl, web.ServerRelativeUrl, site.ServerRelativeUrl));
            string url = Core.ReplaceUrlTokens(customAction.Url, null, null, null, customAction.Feature);
            strings.Add(JavascriptHelper.EscapeChar(url, '\''));
            if (customAction.RequireSiteAdministrator)
                Helper.ConvertULongToInt32HexPair(0x7fffffffffffffffL, out str2, out str3);
            else
                Helper.ConvertULongToInt32HexPair((ulong)SPHelper.ParsePermissions(customAction.Rights), out str2, out str3);
            strings.Add(str2);
            strings.Add(str3);

            if (!string.IsNullOrEmpty(customAction.RegistrationType) && !string.IsNullOrEmpty(customAction.RegistrationId))
            {
                strings.Add(customAction.RegistrationType);
                strings.Add(customAction.RegistrationId);
            }
            else
            {
                strings.Add("ContentType");
                strings.Add("0x");
            }

            strings.Add("200"); // This is the sequence; still to be added

            StringBuilderControl control = new StringBuilderControl();
            control.StringBuilder.Append(JavascriptHelper.ListToJsArray(strings));

            return control;
        }

        #endregion // BuildControl
    }
}
